import { BaseTimer } from "./BaseTimer";
import { Component } from "cc";
import { ComUtil } from "../com/util/ComUtil";
import { EventId, eventMgr } from "../com/EventMgr";

/**
 * 组件基类
 */
export abstract class BaseComp extends Component implements BaseTimer {

    /** 事件监听 */
    eventDic: { [id: number]: (data: any) => any } = {};

    declare callLater: typeof BaseTimer.prototype.callLater;
    declare timerOnce: typeof BaseTimer.prototype.timerOnce;
    declare frameOnce: typeof BaseTimer.prototype.frameOnce;
    declare callTimer: typeof BaseTimer.prototype.callTimer;
    declare clearTimer: typeof BaseTimer.prototype.clearTimer;
    declare clearTimerAll: typeof BaseTimer.prototype.clearTimerAll;

    /**
     * 监听事件 同个事件id只能监听一次 多次监听将覆盖上一次的
     * 通过此方法监听的事件会自动在界面关闭时取消监听
     * @param id 
     * @param callback 
     */
    on<EventId extends keyof EventData>(id: EventId, callback: (data?: EventData[EventId]) => any): void
    on(id: Exclude<EventId, keyof EventData>, callback: () => any): void
    on(id: EventId, callback: (data?: any) => any) {
        this.off(id);
        eventMgr.on(id, callback, this);
    }

    /**
     * 取消监听事件
     * @param id 
     * @returns 
     */
    off(id: EventId) {
        if (!this.eventDic[id]) return;
        eventMgr.off(id, this.eventDic[id], this);
        delete this.eventDic[id];
    }

    /**
     * 取消监听所有事件 onClose的时候会调用一次
     */
    offAll() {
        for (let id in this.eventDic) {
            eventMgr.off(Number(id), this.eventDic[id], this);
        }
        this.eventDic = {};
    }
}
// ComUtil.prototypeExtends(BaseComp, BaseTimer);